package com.mycontract.suitepro.contract

import android.annotation.SuppressLint
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.mycontract.suitepro.base.BaseActivity
import com.mycontract.suitepro.components.dialog.ContractInputPhoneDialog
import com.mycontract.suitepro.contract.adapter.ContractOrderAdapter
import com.mycontract.suitepro.data.ReqGetContractList
import com.mycontract.suitepro.databinding.ActivityContractSuiteContractIndexBinding
import com.mycontract.suitepro.enums.PageTagEnum
import com.mycontract.suitepro.extend.*
import com.mycontract.suitepro.utils.analytics.util.AnalyticsUtil

/** 合同列表页 */
@SuppressLint("CustomSplashScreen")
class ContractIndexActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityContractSuiteContractIndexBinding
    private lateinit var mContractOrderAdapter: ContractOrderAdapter

    //viewModel
    private val mContractViewModel by lazy {
        ViewModelProvider(this)[ContractViewModel::class.java]
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mContractViewModel)
        return list
    }

    override fun onContractSuiteBindingContractSuiteViewContractSuiteTag(): String {
        return PageTagEnum.contract_order_list.name.uppercase()
    }

    override fun onContractSuiteBindingContractSuiteContentContractSuiteView(): View {
        mActivityBinding = ActivityContractSuiteContractIndexBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onContractSuiteContentContractSuiteViewContractSuiteBinded() {
        try {
            //初始化
            initSubViews()

            //获取用户状态回调
            mContractViewModel.onGetContractOrderListLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->

                        // 打点
                        AnalyticsUtil.saveHitPointInfo(
                            type = ContractEvent.ORDER_SEARCH,
                            remark = result.size.toString()
                        )

                        //如果大于1时，不给单独签约
                        result.forEach { item ->
                            item.canSign = true
                        }
                        if (result.size > 1) {
                            result.forEach { item ->
                                item.canSign = false
                            }
                        }

                        // 缓存订单列表
                        ContractSignManager.mOrderList.clear()
                        ContractSignManager.mOrderList.addAll(result)

                        // 缓存订单列表
                        mContractViewModel.mContractOrderList.clear()
                        mContractViewModel.mContractOrderList.addAll(result)

                        // 缓存订单列表
                        mContractViewModel.mContractOrderListTemp.clear()
                        mContractViewModel.mContractOrderListTemp.addAll(result)

                        // 更新页面列表
                        mContractOrderAdapter.notifyDataSetChanged()

                        // 如果没有订单号，显示手机号输入框
                        if (mContractViewModel.mContractOrderList.size > 0) {
                            mActivityBinding.llContractIndexNoOrderBg.visibility = View.GONE
                        } else {
                            mActivityBinding.llContractIndexNoOrderBg.visibility = View.VISIBLE

                            //输入手机号提示框
                            //showPhoneInputDialog()
                        }

                        // 如果订单数大于1，显示一键签约
                        if (mContractViewModel.mContractOrderList.size > 1) {
                            mActivityBinding.llContractSignIndexBottomContent.visibility =
                                View.VISIBLE
                        } else {
                            mActivityBinding.llContractSignIndexBottomContent.visibility =
                                View.GONE
                        }
                    }
                }
            }

            // 搜索
            mActivityBinding.textSearch.setOnClickListener {
                val orderId = mActivityBinding.editSearch.text.toString().trim()
                if (orderId.isNotBlank()) {

                    // 打点
                    AnalyticsUtil.saveHitPointInfo(
                        type = ContractEvent.ORDER_SEARCH,
                        remark = orderId
                    )

                    //获取借款信息
                    getContractOrderList(referrer = orderId)
                }
            }

            // 点击签约
            mActivityBinding.textContractSubmit.setOnClickListener {
                if (mContractViewModel.mContractOrderList.size > 0) {
                    // 去查看合同页
                    toSignContract()
                }
            }

            // 数据声明下划线
            mActivityBinding.textContractDataSafety.addContractSuiteUnderContractSuiteLine()

            // 点击数据声明
            mActivityBinding.llContractDataSafety.setOnClickListener {
                // 打点
                AnalyticsUtil.saveHitPointInfo(
                    type = ContractEvent.DATA_SAFETY,
                    remark = ""
                )

                // 去数据声明页
                startContractSuiteToContractSuiteContractContractSuiteDataContractSuiteSafetyContractSuitePage()
            }

            //查询签约订单
            queryContractOrders()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    /** 初始化 */
    private fun initSubViews() {
        // 手机号
        mActivityBinding.textSearchPhoneHint.text = ContractSignManager.mPhonePreHint

        // 列表
        mContractOrderAdapter = ContractOrderAdapter(mContractViewModel.mContractOrderList)
        mContractOrderAdapter.setContractSuiteOnContractSuiteItemContractSuiteClickContractSuiteListener { _, _ ->
            // 去查看合同页
            toSignContract()
        }

        mActivityBinding.listOrderSigned.layoutManager = LinearLayoutManager(this)
        mActivityBinding.listOrderSigned.adapter = mContractOrderAdapter
    }

    /** 查询用户待签约订单列表 */
    private fun queryContractOrders() {
        /**
        数据回传优先级：
        1、从其它app打开 	    break;
        2、从referrer打开  	break;
        3、从剪贴板打开	  	break;
        4、手动输入 			break;
         */
        if (ContractParamsFromApp.isValidParams()) {
            println("--->1、从其它app打开")
            // 1、从其它app打开
            ContractSignManager.initFormAppParams()

            // 打点
            AnalyticsUtil.saveHitPointInfo(
                type = ContractEvent.OPEN_BY_APP,
                remark = ""
            )

            //获取借款信息
            getContractOrderList(referrer = ContractSignManager.mOrderId)

        } else if (ContractParamsFromClipboard.isValidParams()) {
            println("--->3、从剪贴板打开")
            // 3、从剪贴板打开
            ContractSignManager.initFormClipboardParams()

            // 打点
            AnalyticsUtil.saveHitPointInfo(
                type = ContractEvent.OPEN_BY_CLIPBOARD,
                remark = ""
            )

            //获取借款信息
            getContractOrderList(referrer = ContractSignManager.mOrderId)

        } else {
            println("--->4、手动输入")
            // 4、手动输入

            // 打点
            AnalyticsUtil.saveHitPointInfo(
                type = ContractEvent.OPEN_BY_INPUT,
                remark = ""
            )

            //输入订单号提示框
            showOrderIdInputDialog()
        }
    }

    /** 显示手机号输入框 */
    private fun showOrderIdInputDialog() {
        // 清空搜索内容
        mActivityBinding.editSearch.text = null
        ContractInputPhoneDialog.showContractSuiteDialog(supportFragmentManager) { orderId ->

            // 打点
            AnalyticsUtil.saveHitPointInfo(
                type = ContractEvent.ORDER_INIT_INPUT,
                remark = orderId
            )

            //保存订单号
            ContractSignManager.mOrderId = orderId

            // 获取借款信息
            getContractOrderList(referrer = ContractSignManager.mOrderId)
        }
    }

    /** 获取合同列表 */
    private fun getContractOrderList(referrer: String) {
        //获取借款信息
        val reqGetContractList = ReqGetContractList(referrer = referrer)
        reqGetContractList.showLoading = true;
        mContractViewModel.getContractOrderList(reqGetContractList)
    }

    /** 去签约 */
    private fun toSignContract() {
        // 打点
        AnalyticsUtil.saveHitPointInfo(
            type = ContractEvent.ORDER_INDEX_SIGN,
            remark = ""
        )

        val orderList = mutableListOf<String>()
        val tokenList = mutableListOf<String>()
        val productList = mutableListOf<String>()
        mContractViewModel.mContractOrderList.forEach { item ->
            orderList.add(item.orderId)
            tokenList.add(item.token)
            productList.add(item.product)
        }
        val orderIds = orderList.joinToString(",")
        ContractSignManager.mOrderId = orderIds

        val tokens = tokenList.joinToString(",")
        ContractSignManager.mToken = tokens

        val products = productList.joinToString(",")
        ContractSignManager.mProduct = products

        println("orderIds:$orderIds, token:$tokens, product:$products")

        // 去查看合同页
        startContractSuiteToContractSuiteContractContractSuiteSignContractSuitePage()
    }
}